import {onlineActionTypes} from './online'
import cookies from '../cookie/cookies'
import {userTypes} from './user'
import LoginAPI from '../api/LoginAPI'
import {getStateData} from './store'
import {push} from '../../router/util'
import {toHome} from '../../router/facade'
import {LoginPathByType} from '../env/Constants'
import buyapi from "../api/BuyAPI";

export {authModule, authActionsTypes, authTypes}

//类型，通过commit事件类型触发事件
const authTypes = {
  SET_LOGIN_TYPE: 'SET_LOGIN_TYPE',
  SAVE_AUTH_INFO: 'SAVE_AUTH_INFO',
  LOGOUT: 'LOGOUT',
  SAVE_WX_USER_INFO: 'SAVE_WX_USER_INFO',
  SAVE_AUTH_USERID: 'SAVE_AUTH_USERID',
  THIS_NEED_BIND: 'THIS_NEED_BIND'
}

//类型，通过dispatch事件类型触发事件
const authActionsTypes = {
  LOGIN_BY_SIGN: 'LOGIN_BY_SIGN',
  LOGIN_BY_MOBILE: 'LOGIN_BY_MOBILE',
  LOGIN_BY_WE_CHAT: 'LOGIN_BY_WE_CHAT',
  ON_LOGGED: 'ON_LOGGED',
  LOGOUT: 'LOGOUT',
  CLEAN_LOGGED_INFO: 'CLEAN_LOGGED_INFO',

  LOGIN_BY_TOKEN: 'LOGIN_BY_TOKEN',
  ONLY_SAVE_USERID: 'ONLY_SAVE_USERID',
  STATUS_BUY: 'STATUS_BUY'
}

const authModule = {
  state: {
    loginType: undefined,
    auth: undefined,
    wxInfo: null,
    needBind: false,
  },
  //获取数据
  getters: {
    //Get user info from the cookie,
    auth: (state) => getStateData(state, 'auth', cookies.keys.KEY_AUTH, authTypes.SAVE_AUTH_INFO),
    userid: (state, getters) => getters.auth.userid,
    token: (state, getters) => getters.auth.token,
    loginType: (state, getters) => state.loginType,
    hasLogged: (state, getters) => !!getters.auth.token,
    wxInfo: (state) => getStateData(state, 'wxUserInfo', cookies.keys.KEY_WX_USER_INFO, authTypes.SAVE_WX_USER_INFO),
    openId: (state, getters) => getters.wxInfo.openid,
    unionId: (state, getters) => getters.wxInfo.unionid,
    canEnterMyInfo: (state) => {
      return state.loginType === 'wx' || state.loginType === 'wxpc';
    }
  },
//同步请求，只有这里能修改数据
  mutations: {
    [authTypes.THIS_NEED_BIND](state, type) {
      state.needBind = type
    },
    [authTypes.SET_LOGIN_TYPE](state, loginType) {
      if (loginType) {
        state.loginType = loginType
      }
    },
    [authTypes.SAVE_AUTH_INFO](state, auth) {
      if (!auth || !auth.token || !auth.userid) return
      let data = {'token': auth.token, 'userid': auth.userid}
      state.auth = data
      cookies.saveAuth(data)
    },
    [authTypes.SAVE_AUTH_USERID](state, auth) {
      let data = {'userid': auth.userid}
      state.auth = data
      cookies.saveAuth(data)
    },
    [authTypes.SAVE_WX_USER_INFO](state, data) {
      state.wxInfo = data
      cookies.saveWxInfo(data)
    },
    //登出
    [authTypes.LOGOUT](state) {
      state.auth = null
      state.wxInfo = null
    },
  },
//异步请求
  actions: {
    [authActionsTypes.ON_LOGGED]({dispatch}) {
      dispatch(`online/${onlineActionTypes.UPDATE_ONLINE_DATA}`)
    },
    [authActionsTypes.CLEAN_LOGGED_INFO](store, data) {
      cookies.clearAll()
      store.commit(authTypes.LOGOUT)
      console.log('clear cookies success')
    },
    [authActionsTypes.LOGOUT]({state, dispatch}, data) {
      dispatch(authActionsTypes.CLEAN_LOGGED_INFO, data)
        .finally(() => {
          return push(LoginPathByType[state.loginType])
        })
    },
    //手机号码登录
    [authActionsTypes.LOGIN_BY_MOBILE]({commit, dispatch}, data) {
      let mobile = data.mobile
      let authCode = data.authCode
      return dispatch(authActionsTypes.CLEAN_LOGGED_INFO)
        .then(() => LoginAPI.login(mobile, authCode))
        .then(result => {
          let user = result.responseData
          commit(authTypes.SAVE_AUTH_INFO, user)
          commit(userTypes.SAVE_USER_INFO, user)
          return result
        })
        .then(() => toHome())
    },

    //微信登录
    [authActionsTypes.LOGIN_BY_WE_CHAT]({commit, dispatch}, data) {
      let {wxInfo} = data
      return dispatch(authActionsTypes.CLEAN_LOGGED_INFO)
        .then(() => LoginAPI.loginByWx(wxInfo))
        .then(result => {
          let user = result.responseData
          commit(authTypes.SAVE_AUTH_INFO, user)
          commit(userTypes.SAVE_USER_INFO, user)
          commit(authTypes.SAVE_WX_USER_INFO, wxInfo)
          return result

        })
    },
    //sign登录
    [authActionsTypes.LOGIN_BY_SIGN]({commit, dispatch}, data) {
      return dispatch(authActionsTypes.CLEAN_LOGGED_INFO)
        .then(() => {
          let sign = data.sign
          cookies.saveSign(sign)
          return LoginAPI.loginBySign(sign)
        })
        .then((result) => {
            let user = result.responseData
            commit(authTypes.SAVE_AUTH_INFO, user)
            commit(userTypes.SAVE_USER_INFO, user)
            return result
          }
        )
    },
    //判断是否购买过
    [authActionsTypes.STATUS_BUY]({commit, dispatch}, data) {
      buyapi.isPurchasedVIP(data).then(result => {
        return result
      })
    },

    //只是保存一个userId
    [authActionsTypes.ONLY_SAVE_USERID]({commit, dispatch}, data) {
      commit(authTypes.SAVE_AUTH_USERID, data)
    }
  }

}


